<template>
  <el-dialog
    class="nodeNoteDialog"
    title="备注"
    v-model="dialogVisible"
    :width="isMobile ? '90%' : '50%'"
    :top="isMobile ? '20px' : '15vh'"
  >
    <!-- <el-input
      type="textarea"
      :autosize="{ minRows: 3, maxRows: 5 }"
      placeholder="请输入内容"
      v-model="note"
    >
    
    </el-input> -->
    <div class="noteEditor" ref="noteEditor" @keyup.stop @keydown.stop />
    <!-- <div class="tip">换行请使用：Enter+Shift</div> -->
    <template v-slot:footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="confirm">确认</el-button>
    </template>
  </el-dialog>
</template>

<script>
import Editor from "@toast-ui/editor"
import "@toast-ui/editor/dist/toastui-editor.css" // Editor's Style
import { isMobile } from "simple-mind-map/src/utils/index"

export default {
  name: "NodeNote",
  data() {
    return {
      dialogVisible: false,
      note: "",
      activeNodes: [],
      editor: null,
      isMobile: isMobile()
    }
  },
  watch: {
    dialogVisible(val, oldVal) {
      if (!val && oldVal) {
        this.$bus.$emit("endTextEdit")
      }
    }
  },
  created() {
    this.$bus.$on("node_active", this.handleNodeActive)
    this.$bus.$on("showNodeNote", this.handleShowNodeNote)
  },
  beforeUnmount() {
    this.$bus.$off("node_active", this.handleNodeActive)
    this.$bus.$off("showNodeNote", this.handleShowNodeNote)
  },
  methods: {
    handleNodeActive(args) {
      if (args) {
        this.activeNodes = [...args[1]]
        if (this.activeNodes.length > 0) {
          const firstNode = this.activeNodes[0]
          this.note = firstNode.getData("note") || ""
        } else {
          this.note = ""
        }
      } else {
        this.activeNodes = null
      }
    },

    handleShowNodeNote() {
      this.$bus.$emit("startTextEdit")
      this.dialogVisible = true
      this.$nextTick(() => {
        this.initEditor()
      })
    },

    initEditor() {
      if (!this.editor) {
        this.editor = new Editor({
          el: this.$refs.noteEditor,
          height: "500px",
          initialEditType: "markdown",
          previewStyle: "vertical"
        })
        this.editor.setHTML(this.note)
      }
    },

    cancel() {
      this.dialogVisible = false
    },

    confirm() {
      this.note = this.editor.getMarkdown()
      this.activeNodes.forEach((node) => {
        node.setNote(this.note)
      })
      this.cancel()
    }
  }
}
</script>

<style lang="less" scoped>
.nodeNoteDialog {
  .tip {
    margin-top: 5px;
    color: #dcdfe6;
  }
}
</style>
